package com.neusoft.elm.infrastructure.util;

import com.neusoft.elm.infrastructure.config.AppConfig;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DBUtil {
    private static final ThreadLocal<Connection> TL = new ThreadLocal<>();
    
    // 获取Connection
    public static Connection getConnection() {
        Connection con = TL.get();
        if (con == null) {
            con = createConnection();
            TL.set(con);
        }
        return con;
    }

    // 开启一个事务
    public static void beginTransaction() throws Exception {
        Connection con = getConnection();
        con.setAutoCommit(false);
    }

    // 提交一个事务
    public static void commitTransaction() throws Exception {
        Connection con = TL.get();
        if (con != null) {
            con.commit();
        }
    }

    // 回滚一个事务
    public static void rollbackTransaction() throws Exception {
        Connection con = TL.get();
        if (con != null) {
            con.rollback();
        }
    }

    // 关闭各种资源
    public static void close(ResultSet rs, PreparedStatement pst) {
        try {
            if (rs != null) {
                rs.close();
            }
            if (pst != null) {
                pst.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // 关闭各种资源
    public static void close(PreparedStatement pst) {
        try {
            if (pst != null) {
                pst.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // 关闭连接
    public static void close() {
        Connection con = TL.get();
        try {
            if (con != null) {
                con.close();
            }
            TL.remove();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private static Connection createConnection() {
        Connection con = null;
        try {
            Class.forName(AppConfig.getDbDriver());
            con = DriverManager.getConnection(
                AppConfig.getDbUrl(),
                AppConfig.getDbUsername(),
                AppConfig.getDbPassword()
            );
        } catch (Exception e) {
            throw new RuntimeException("创建数据库连接失败", e);
        }
        return con;
    }
} 